<?php
/**
 * Created by PhpStorm.
 * User: zhongbaitong
 * Date: 2020/1/13
 * Time: 14:20
 */

namespace app\im\model;

/**
 * @method hasMany(string $string, string $string1)
 */
class ChatRoot extends ImBase
{
    // 聊天列表
    public function lists(){
        return $this->hasMany("ChatLists","root_id");
    }

    // 聊天记录
    public function chat(){
        return $this->hasMany("Chat","root_id");
    }

    // 初始化
    public static function chatInit($params){

        $user_id   = $params["user_id"];
        $obj_uid   = $params["obj_uid"];
        $root_type = $params["root_type"] ?? 1;

        // 查询两人的房间号
        if(!$root_id = ChatLists::getRootID($user_id,$obj_uid)){
            // 无则初始化
            $root = new ChatRoot;
            $root->type  = $root_type;
            $root->title = "U-".$user_id."-".$obj_uid;
            $root->save();

            if($user_id == $obj_uid){
                $data = [[
                    "user_id" => $user_id,
                    "is_self" => 1
                ]];
            }
            else{
                $data = [
                    ['user_id' => $user_id],
                    ['user_id' => $obj_uid],
                ];
            }

            $root->lists()->saveAll($data);
            $root_id = $root->id;
        }

        return $root_id;
    }
}